""""""
import os
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from tencentcloud.common import credential
from tencentcloud.tmt.v20180321 import tmt_client, models


class ContainsAnyDict(dict):
    def __init__(self, type):
        self.type = type

    def __getitem__(self, key):
        return (self.type, )

    def __contains__(self, key):
        return True


class Util:

    @staticmethod
    def scale_bbox(bbox: list, scale_width=1, scale_height=1):
        bbox_x1, bbox_y1, bbox_x2, bbox_y2 = bbox
        c_x, c_y = int((bbox_x1 + bbox_x2) / 2), int((bbox_y1 + bbox_y2) / 2)
        width = (bbox_x2 - bbox_x1) * scale_width
        height = (bbox_y2 - bbox_y1) * scale_height
        half_width = int(width / 2)
        half_height = int(height / 2)
        bbox_x1, bbox_x2 = c_x - half_width, c_x + half_width
        bbox_y1, bbox_y2 = c_y - half_height, c_y + half_height
        if bbox_x1 < 0:
            bbox_x1 = 0
        if bbox_y1 < 0:
            bbox_y1 = 0
        return (bbox_x1, bbox_y1, bbox_x2, bbox_y2)

    @staticmethod
    def draw(img: Image.Image, det_results: list[dict], draw_kps=False):
        """, output_filename: str"""
        _, img_w, _ = np.array(img).shape
        draw = ImageDraw.Draw(img)
        m = int(img_w / 1000) + 1
        for result in det_results:
            score = result['det_score']
            if type(score) is not str:
                score = round(result['det_score'] * 100, 2)
            bbox_x1, bbox_y1, bbox_x2, bbox_y2 = result["bbox"]
            c_w = len(str(score)) * 12
            bk_x2, bk_y2 = bbox_x1 + c_w * m, bbox_y1 + 26 * m
            if bk_x2 > bbox_x2:
                bk_x2 = bbox_x2
            if bk_y2 > bbox_y2:
                bk_y2 = bbox_y2
            fill_blank = (bbox_x1, bbox_y1, bk_x2, bk_y2)
            draw.rectangle(fill_blank, outline='white', width=1, fill='white')
            font = ImageFont.load_default(size=20 * m)
            draw.text((bbox_x1 + 5 * m, bbox_y1 + 3 * m), f"{score}", font=font, fill=(255, 0, 0))
            draw.rectangle((bbox_x1, bbox_y1, bbox_x2, bbox_y2), outline='red', width=2 * m)
            draw.rectangle((bbox_x1, bbox_y1, bbox_x2, bbox_y2), outline='red', width=2 * m)
            if "kps" in result and draw_kps:
                for p in result["kps"]:
                    p_x, p_y = int(p[0]), int(p[1])
                    draw.rectangle((p_x, p_y, p_x + 4 * m, p_y + 4 * m), outline='red', width=1, fill='red')
        return img
    
    @staticmethod
    def pil2tensor(image: Image.Image) -> torch.Tensor:
        np_image = np.array(image).astype(np.float32) / 255.0
        return torch.from_numpy(np_image)
    
    @staticmethod
    def tensor2pil(image: torch.Tensor) -> Image.Image:
        i = 255. * image.cpu().numpy()
        return Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
    
    @staticmethod
    def get_root():
        return os.path.abspath(os.path.dirname(__file__))
    

class TencentTranslate:

    def __init__(self, secret_id: str, secret_key: str, region='ap-shanghai'):
        cred = credential.Credential(secret_id=secret_id, secret_key=secret_key)
        self.client = tmt_client.TmtClient(credential=cred, region=region)

    def translate(self, text: str, source='zh', target='en') -> str:
        request = models.TextTranslateRequest()
        request.SourceText = text
        request.Source = source
        request.Target = target
        request.ProjectId = 0
        response = self.client.TextTranslate(request)
        return response.TargetText
